In [25]:
# ================================================================
# LAB 14. LOGISTIC REGRESSION
#
# STAT 415/615 - Regression
#
# Topics:
# 1. Preparing data for logistic regression
# 2. Fitting a logistic regression model
# 3. Interpreting coefficients and significance tests
# 4. Classification and training error
# 5. Predicting probabilities for new observations
#
# ================================================================
# ================================================================
# PART 0. PREPARATION
# ================================================================
# Import the required libraries.
#
# pandas: data manipulation
# numpy: numerical calculations
# statsmodels: logistic regression
# scipy: logistic function
# sklearn: classification accuracy and confusion matrix
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy.special import expit
from sklearn.metrics import (
accuracy_score,
confusion_matrix
)
# ------------------------------------------------
# Load the depression dataset
# ------------------------------------------------
# The dataset Depr contains information about students:
#
# ID Student identifier
# Gender Gender of the student
# Guardian_status Guardian status
# Cohesion_score Connection to community
# Depression_score Depression assessment score
# Diagnosis Binary depression diagnosis
#
# Diagnosis = 1 indicates a positive diagnosis.
# Diagnosis = 0 indicates a negative diagnosis.
#
# The dataset is not included in standard Python libraries.
#
# Upload its CSV file using the Colab file chooser.
# The file will be read automatically after uploading.
Depr = pd.read_csv(
"https://dr-baron.github.io/415-615/Data/depression_data.csv"
)
# Examine the variable names.
print("\nVARIABLE NAMES")
print(Depr.columns.tolist())
# Examine the first observations.
print("\nFIRST OBSERVATIONS")
print(Depr.head())
VARIABLE NAMES ['ID', 'Gender', 'Guardian_status', 'Cohesion_score', 'Depression_score', 'Diagnosis'] FIRST OBSERVATIONS ID Gender Guardian_status Cohesion_score Depression_score Diagnosis 0 1 Male 1 80.0 3 NaN 1 2 Male 1 57.1 17 NaN 2 3 Male 0 36.3 17 NaN 3 4 Female 1 44.0 17 NaN 4 5 Male 0 46.0 19 NaN
In [26]:
# ================================================================
# PART 1. PREPARING THE DATA
# ================================================================
# The response variable Diagnosis contains many
# missing values.
#
# Logistic regression cannot be fitted using
# observations with missing values in the variables
# included in the model.
#
# We therefore remove incomplete observations.
#
# This is equivalent to na.omit(Depr) in R.
# ------------------------------------------------
# 1A. Examine the response variable
# ------------------------------------------------
print("\nDIAGNOSIS SUMMARY")
print(Depr["Diagnosis"].describe())
print("\nNUMBER OF MISSING DIAGNOSES")
print(Depr["Diagnosis"].isna().sum())
# ------------------------------------------------
# 1B. Remove missing observations
# ------------------------------------------------
# Remove rows containing missing values in any column.
#
# This reproduces the behavior of R's na.omit(Depr).
Depr1 = Depr.dropna().copy()
# Examine the dimensions of the complete dataset.
print("\nDIMENSIONS AFTER REMOVING MISSING VALUES")
print(Depr1.shape)
# Examine the distribution of Diagnosis.
print("\nDIAGNOSIS COUNTS")
print(Depr1["Diagnosis"].value_counts().sort_index())
DIAGNOSIS SUMMARY count 458.000000 mean 0.157205 std 0.364392 min 0.000000 25% 0.000000 50% 0.000000 75% 0.000000 max 1.000000 Name: Diagnosis, dtype: float64 NUMBER OF MISSING DIAGNOSES 2731 DIMENSIONS AFTER REMOVING MISSING VALUES (458, 6) DIAGNOSIS COUNTS Diagnosis 0.0 386 1.0 72 Name: count, dtype: int64
In [27]:
# ================================================================
# PART 2. FITTING A LOGISTIC REGRESSION MODEL
# ================================================================
# Logistic regression is used when the response
# variable is binary.
#
# Let:
#
# p = P(Diagnosis = 1 | predictors)
#
# The logistic regression model is:
#
# log(p / (1-p))
# = b0 + b1*GenderMale
# + b2*Guardian_status
# + b3*Cohesion_score
#
# The left-hand side is called the logit.
#
# Logistic regression models the log-odds of a
# positive diagnosis as a linear function of
# the predictors.
#
# Unlike ordinary linear regression, the fitted
# probabilities are constrained to lie between
# 0 and 1.
# ------------------------------------------------
# 2A. Fit the logistic regression
# ------------------------------------------------
# C(Gender, Treatment(reference="Female")) specifies
# that Gender is categorical and Female is the
# reference category.
#
# Guardian_status is treated as a numerical predictor,
# as in the original R lab.
#
# statsmodels uses maximum likelihood estimation
# to estimate the regression coefficients.
fit = smf.logit(
'Diagnosis ~ C(Gender, Treatment(reference="Female"))'
' + Guardian_status + Cohesion_score',
data=Depr1
).fit(disp=False)
# Display the regression summary.
print("\nLOGISTIC REGRESSION SUMMARY")
print(fit.summary())
# ------------------------------------------------
# 2B. Coefficients and significance tests
# ------------------------------------------------
# The regression summary contains:
#
# coef Estimated regression coefficient
# std err Standard error
# z Wald z-statistic
# P>|z| Two-sided p-value
#
# The Wald statistic is:
#
# z = estimated coefficient / standard error
#
# Under H0: beta_j = 0, the statistic has
# approximately a standard normal distribution.
#
# Small p-values indicate evidence that a predictor
# is associated with the response, conditional on
# the other predictors in the model.
coefficients = pd.DataFrame({
"Estimate": fit.params,
"Std. Error": fit.bse,
"z value": fit.tvalues,
"p-value": fit.pvalues
})
print("\nPARAMETER ESTIMATES")
print(coefficients.round(5))
# ------------------------------------------------
# 2C. Odds ratios
# ------------------------------------------------
# The exponential of a logistic regression
# coefficient is an odds ratio.
#
# For a one-unit increase in a numerical predictor,
# holding the other predictors constant:
#
# Odds ratio = exp(beta_j)
#
# An odds ratio below 1 indicates decreasing odds
# of a positive diagnosis as the predictor increases.
#
# An odds ratio above 1 indicates increasing odds.
#
# For Gender, the odds ratio compares Male with
# the reference category Female.
odds_ratios = np.exp(fit.params)
print("\nODDS RATIOS")
print(odds_ratios.round(4))
LOGISTIC REGRESSION SUMMARY
Logit Regression Results
==============================================================================
Dep. Variable: Diagnosis No. Observations: 458
Model: Logit Df Residuals: 454
Method: MLE Df Model: 3
Date: Wed, 28 Oct 2026 Pseudo R-squ.: 0.09559
Time: 17:15:18 Log-Likelihood: -180.19
converged: True LL-Null: -199.23
Covariance Type: nonrobust LLR p-value: 2.705e-08
====================================================================================================================
coef std err z P>|z| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
Intercept 1.0083 0.505 1.998 0.046 0.019 1.998
C(Gender, Treatment(reference="Female"))[T.Male] -0.6874 0.288 -2.383 0.017 -1.253 -0.122
Guardian_status -0.7484 0.286 -2.616 0.009 -1.309 -0.188
Cohesion_score -0.0436 0.010 -4.167 0.000 -0.064 -0.023
====================================================================================================================
PARAMETER ESTIMATES
Estimate Std. Error \
Intercept 1.00832 0.50478
C(Gender, Treatment(reference="Female"))[T.Male] -0.68744 0.28848
Guardian_status -0.74835 0.28602
Cohesion_score -0.04358 0.01046
z value p-value
Intercept 1.99752 0.04577
C(Gender, Treatment(reference="Female"))[T.Male] -2.38293 0.01718
Guardian_status -2.61643 0.00889
Cohesion_score -4.16702 0.00003
ODDS RATIOS
Intercept 2.7410
C(Gender, Treatment(reference="Female"))[T.Male] 0.5029
Guardian_status 0.4731
Cohesion_score 0.9574
dtype: float64
In [28]:
# ================================================================
# PART 3. CLASSIFICATION AND TRAINING ERROR
# ================================================================
# We now evaluate how well the fitted model
# classifies observations in the training data.
#
# IMPORTANT:
# These observations were used to estimate the
# regression coefficients.
#
# Therefore, this is an evaluation of training
# accuracy, not cross-validation.
#
# A separate testing sample or cross-validation
# would be needed to evaluate out-of-sample accuracy.
# ------------------------------------------------
# 3A. Predicted probabilities
# ------------------------------------------------
# The predict() method returns fitted probabilities:
#
# Prob_i = P(Diagnosis_i = 1 | predictors)
#
# Each probability is between 0 and 1.
Prob = fit.predict(Depr1)
print("\nSUMMARY OF PREDICTED PROBABILITIES")
print(Prob.describe())
# ------------------------------------------------
# 3B. Classify observations
# ------------------------------------------------
# We classify a student as having a positive
# diagnosis when the predicted probability
# exceeds 0.30.
#
# Otherwise, the predicted diagnosis is 0.
#
# The threshold 0.30 is chosen for illustration.
# It is not a validated clinical decision threshold.
YesPredict = (Prob > 0.30).astype(int)
# ------------------------------------------------
# 3C. Confusion matrix
# ------------------------------------------------
# A confusion matrix compares the actual and
# predicted classifications.
#
# Rows represent actual diagnoses.
# Columns represent predicted diagnoses.
#
# The four possible outcomes are:
#
# True negative: Actual 0, Predicted 0
# False positive: Actual 0, Predicted 1
# False negative: Actual 1, Predicted 0
# True positive: Actual 1, Predicted 1
table = pd.crosstab(
Depr1["Diagnosis"],
YesPredict,
rownames=["Actual diagnosis"],
colnames=["Predicted diagnosis"]
)
print("\nCONFUSION MATRIX")
print(table)
# ------------------------------------------------
# 3D. Classification accuracy
# ------------------------------------------------
# Accuracy is the proportion of correctly
# classified observations:
#
# Accuracy = (TN + TP) / n
#
# Training error is:
#
# Training error = 1 - Accuracy
accuracy = accuracy_score(
Depr1["Diagnosis"],
YesPredict
)
training_error = 1 - accuracy
print("\nCLASSIFICATION ACCURACY")
print("Accuracy:", round(accuracy, 4))
print("Training error:", round(training_error, 4))
# ------------------------------------------------
# 3E. Sensitivity and specificity
# ------------------------------------------------
# Overall accuracy can be misleading when one
# response category is much more common.
#
# Sensitivity measures the proportion of actual
# positive diagnoses correctly identified.
#
# Sensitivity = TP / (TP + FN)
#
# Specificity measures the proportion of actual
# negative diagnoses correctly identified.
#
# Specificity = TN / (TN + FP)
TN, FP, FN, TP = confusion_matrix(
Depr1["Diagnosis"],
YesPredict,
labels=[0, 1]
).ravel()
sensitivity = TP / (TP + FN)
specificity = TN / (TN + FP)
print("\nSENSITIVITY AND SPECIFICITY")
print("Sensitivity:", round(sensitivity, 4))
print("Specificity:", round(specificity, 4))
SUMMARY OF PREDICTED PROBABILITIES count 458.000000 mean 0.157205 std 0.107530 min 0.019576 25% 0.074524 50% 0.129931 75% 0.215602 max 0.577148 dtype: float64 CONFUSION MATRIX Predicted diagnosis 0 1 Actual diagnosis 0.0 359 27 1.0 48 24 CLASSIFICATION ACCURACY Accuracy: 0.8362 Training error: 0.1638 SENSITIVITY AND SPECIFICITY Sensitivity: 0.3333 Specificity: 0.9301
In [29]:
# ================================================================
# PART 4. PREDICTION FOR NEW OBSERVATIONS
# ================================================================
# Logistic regression can predict the probability
# of a positive diagnosis for a new observation.
#
# First, the regression model calculates the logit:
#
# eta = b0 + b1*x1 + b2*x2 + b3*x3
#
# The logit is converted into a probability using
# the logistic function:
#
# p = exp(eta) / (1 + exp(eta))
#
# Equivalently:
#
# p = 1 / (1 + exp(-eta))
#
# scipy.special.expit() calculates this probability
# accurately, including for very large logits.
# ------------------------------------------------
# 4A. Prediction for a student with low cohesion
# ------------------------------------------------
# Consider a female student with:
#
# Gender = Female
# Guardian_status = 1
# Cohesion_score = 26
#
# This represents a student with a low
# community cohesion score.
student1 = pd.DataFrame({
"Gender": ["Female"],
"Guardian_status": [1],
"Cohesion_score": [26]
})
# Predict the logit.
#
# linear=True returns the linear predictor
# rather than the probability.
logit1 = fit.predict(student1, which="linear").iloc[0]
print("\nPREDICTED LOGIT")
print(logit1)
# Convert the logit into a probability.
P1 = expit(logit1)
print("\nPREDICTED PROBABILITY")
print(P1)
# ------------------------------------------------
# 4B. Predict probability directly
# ------------------------------------------------
# By default, predict() returns the probability
# rather than the logit.
#
# This is equivalent to:
#
# predict(fit, newdata=student1, type="response")
#
# in R.
P1_direct = fit.predict(student1).iloc[0]
print("\nDIRECTLY PREDICTED PROBABILITY")
print(P1_direct)
# ------------------------------------------------
# 4C. Prediction with average cohesion
# ------------------------------------------------
# Now consider the same student, but with
# Cohesion_score = 52.
#
# All other predictors remain unchanged.
student2 = pd.DataFrame({
"Gender": ["Female"],
"Guardian_status": [1],
"Cohesion_score": [52]
})
P2 = fit.predict(student2).iloc[0]
print("\nPREDICTION WITH HIGHER COHESION")
print("Cohesion score 26:", round(P1, 4))
print("Cohesion score 52:", round(P2, 4))
PREDICTED LOGIT -0.8730465531149785 PREDICTED PROBABILITY 0.2946207733348972 DIRECTLY PREDICTED PROBABILITY 0.2946207733348972 PREDICTION WITH HIGHER COHESION Cohesion score 26: 0.2946 Cohesion score 52: 0.1186
In [30]:
# ================================================================
# PART 5. VISUALIZATION
# ================================================================
# We can visualize how the predicted probability
# changes with the community cohesion score.
#
# We keep Gender = Female and Guardian_status = 1
# fixed while varying Cohesion_score.
#
# The resulting curve is nonlinear, even though
# Cohesion_score enters linearly in the logit.
import matplotlib.pyplot as plt
cohesion_values = np.linspace(
Depr1["Cohesion_score"].min(),
Depr1["Cohesion_score"].max(),
200
)
new_students = pd.DataFrame({
"Gender": ["Female"] * len(cohesion_values),
"Guardian_status": [1] * len(cohesion_values),
"Cohesion_score": cohesion_values
})
probabilities = fit.predict(new_students)
plt.figure(figsize=(8, 5))
plt.plot(
cohesion_values,
probabilities
)
plt.scatter(
[26, 52],
[P1, P2],
color="red",
zorder=3
)
plt.xlabel("Community cohesion score")
plt.ylabel("Predicted probability of positive diagnosis")
plt.title("Logistic Regression: Predicted Probability")
plt.ylim(0, 1)
plt.grid(alpha=0.3)
plt.show()
In [ ]:
# ================================================================
# PART 6. EXPORT THE NOTEBOOK TO HTML AND IPYNB
# ================================================================
# This section saves the current Google Colab notebook
# in two formats:
#
# HTML:
# A readable document containing the Python code,
# explanatory comments, tables, and graphical output.
#
# IPYNB:
# An executable Jupyter notebook that can be opened
# and edited in Google Colab or Jupyter.
#
# Run this section AFTER executing all previous cells.
#
# Both files will be downloaded to your computer.
#
# Your browser's download settings determine where
# the files are saved.
from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat
import json
# Retrieve the current Google Colab notebook.
notebook = _message.blocking_request(
"get_ipynb",
timeout_sec=60
)["ipynb"]
# Convert the notebook to standard Jupyter format.
nb = nbformat.reads(
notebook if isinstance(notebook, str)
else json.dumps(notebook),
as_version=4
)
# Specify the common filename for both versions.
filename = "Py Lab 14 - Logistic Regression"
# ------------------------------------------------
# Save the executable Jupyter notebook
# ------------------------------------------------
with open(filename + ".ipynb", "w", encoding="utf-8") as f:
nbformat.write(nb, f)
# ------------------------------------------------
# Convert the notebook to HTML
# ------------------------------------------------
html, resources = HTMLExporter().from_notebook_node(nb)
# Save the HTML document.
with open(filename + ".html", "w", encoding="utf-8") as f:
f.write(html)
# ------------------------------------------------
# Download both files
# ------------------------------------------------
files.download(filename + ".html")
files.download(filename + ".ipynb")
# ================================================================
# END OF LAB 14
# ================================================================
In [ ]: